package com.arvato.wxwork.service.dictionary;


import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.arvato.minipro.bean.bean_dto.common.PageData;
import com.arvato.minipro.bean.bean_dto.common.Query;
import com.arvato.common.ftp.FtpTool;
import com.arvato.wxwork.bean.bean_do.dictionary.WxworkPromotionDo;
import com.arvato.wxwork.bean.bean_vo.dictionary.WxworkPromotionVo;
import com.arvato.wxwork.mapper.dictionary.WxworkPromotionMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;


@Service
@Transactional
public class WxworkPromotionService {
	
	@Autowired
	private WxworkPromotionMapper wxworkPromotionMapper;
	@Autowired
	private FtpTool ftpTool;
	/**
	 * 批量查询推广信息
	 * @param query
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	public PageData listPromotionByQuery(Query query, Integer pageNum, Integer pageSize) {
		PageHelper.startPage(pageNum, pageSize);
		List<WxworkPromotionVo> promotionList = wxworkPromotionMapper.listPromotionByQuery(query);
		PageInfo<WxworkPromotionVo> pageInfo = new PageInfo<WxworkPromotionVo>(promotionList);
		return new PageData(pageInfo.getTotal(), pageInfo.getList());
	}
	/**
	 * 根据Id查询推广活动
	 * @param promotionId
	 */
	public WxworkPromotionVo getPromotionById(String promotionId) {
		return wxworkPromotionMapper.getPromotionById(promotionId);
	}
	/**
	 * 新增一个活动推广
	 * @param promotionDo
	 * @return
	 */
	public int insert(WxworkPromotionDo promotionDo) {
		return wxworkPromotionMapper.insert(promotionDo);
	}
	/**
	 * 修改一个活动推广
	 * @param promotionDo
	 * @return
	 */
	public int update(WxworkPromotionDo promotionDo) {
		String fileName = null;
		if(promotionDo.getImgUrl() != null) {
			WxworkPromotionVo wxworkPromotionVo = wxworkPromotionMapper.getPromotionById(promotionDo.getPromotionId());
			// 如果修改了图片 将以前的图片删掉
			System.out.println(wxworkPromotionVo.getImgUrl());
			fileName = wxworkPromotionVo.getImgUrl().split("fileName=")[1];
		}
		int row = wxworkPromotionMapper.update(promotionDo);
		if(row == 1 && fileName != null) {
			ftpTool.delete(fileName);
		}
		return row;
	}
	/**
	 * 删除一个活动推广
	 * @param promotionId
	 * @return
	 */
	public int delete(String promotionId) {
		// 先将需要删除的查询出来
		WxworkPromotionVo wxworkPromotionVo = wxworkPromotionMapper.getPromotionById(promotionId);
		String fileName = wxworkPromotionVo.getImgUrl().split("fileName=")[1];
		int row = wxworkPromotionMapper.delete(promotionId);
		if(row == 1) {
			ftpTool.delete(fileName);
		}
		return row;
	}
	
}
